package com.wan37.client;

import com.googlecode.protobuf.format.JsonFormat;
import com.wan37.client.global.reference.SpringContextHolder;
import com.wan37.client.handler.ClientHandler;
import com.wan37.client.service.cache.*;
import com.wan37.common.uuid.UUIDUtil;
import com.wan37.protobuf.constant.*;
import com.wan37.protobuf.message.client2server.game.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.Id;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

/**
 * 控制台指令中心
 *
 * @author : luoyong
 * @date : 2020-05-28 15:45
 **/
public class Order implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(Order.class);
    private WeaponryServiceCache weaponryServiceCache;
    private ItemServiceCache itemServiceCache;
    private CommodityServiceCache commodityServiceCache;
    private RoleServiceCache roleServiceCache;
    private UserServiceCache userServiceCache;
    private ClientHandler clientHandler = Client.clientHandler;
    private GuildCache guildCache;
    private TradingShopCache tradingShopCache;

    @Override
    public void run() {
        doOrder();
    }

    public void doOrder() {
        this.weaponryServiceCache = SpringContextHolder.getBean("weaponryServiceCache");
        this.itemServiceCache = SpringContextHolder.getBean("itemServiceCache");
        this.commodityServiceCache = SpringContextHolder.getBean("commodityServiceCache");
        this.roleServiceCache = SpringContextHolder.getBean("roleServiceCache");
        this.userServiceCache = SpringContextHolder.getBean("userServiceCache");
        this.guildCache = SpringContextHolder.getBean("guildCache");
        this.tradingShopCache = SpringContextHolder.getBean("tradingShopCache");
        while (true) {
            logger.info("\n请输入相应指令选择对应操作:\n 1、注册\t\t\t 2、登入\n 3、切换场景\t\t" +
                    " 4、与场景内实体进行互动\n 5、个人背包\t\t 6、商城\n 7、世界聊天\t\t 8、创建角色\n" +
                    " 9、邮件\t\t\t 10、组队管理\n 11、面对面交易\t 12、公会\n 13、交易行\t\t 14、查看当前成就进度");
            Scanner sc = new Scanner(System.in);
            String s = sc.nextLine();
            if (s == null || s.length() == 0 || !isNumeric(s)) {
                logger.info("非法输入，请重新选择！");
                continue;
            }
            int code = Integer.parseInt(s);
            switch (code) {
                case 1:
                    logger.info("请输入账号：");
                    String userId = sc.nextLine();
                    logger.info("请输入密码：");
                    String password = sc.nextLine();
                    logger.info("请输入昵称：");
                    String nickname = sc.nextLine();
                    clientHandler.registerAccount(userId, password, nickname);
                    break;
                case 2:
                    if (isLoginAndIsRole()) {
                        logger.info("用户已登录，请注销后再操作！！");
                        break;
                    }
                    logger.info("请输入账号：");
                    String userId1 = sc.nextLine();
                    logger.info("请输入密码：");
                    String password1 = sc.nextLine();
                    clientHandler.login(userId1, password1);
                    break;
                case 3:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    logger.info("请输入要移动到的位置：");
                    String next_scene = sc.nextLine();
                    clientHandler.sendMoveMessage(next_scene);
                    break;
                case 4:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    if (ClientHandler.allRoleMap.isEmpty() && roleServiceCache.getRoleInMap().isEmpty()) {
                        logger.info("当前场景没有实体！！");
                        break;
                    }
                    while (true) {
                        for (GameEntity.AllRole allRole : ClientHandler.allRoleMap.values()) {
                            System.out.println(allRole.getAllRoleId() + ": " + JsonFormat.printToString(allRole));
                        }
                        for (RoleServiceCache.RoleIn roleIn : roleServiceCache.getRoleInMap().values()) {
                            System.out.println(roleIn.getRole().getAllRole().getAllRoleId() + ": " + JsonFormat.printToString(roleIn.getRole()));
                        }
                        System.out.println(0 + ": 返回主菜单");
                        System.out.println("请选择对于的序号进行操作！");
                        String s1 = sc.nextLine();
                        if ("0".equals(s1)) {
                            break;
                        }
                        if (s1 == null || s1.length() == 0 || !Order.isNumeric(s1)
                                || (!ClientHandler.allRoleMap.containsKey(s1)
                                && !roleServiceCache.getRoleInMap().containsKey(s1))) {
                            logger.info("非法输入，请重新选择！");
                            continue;
                        }
                        if (ClientHandler.allRoleMap.containsKey(s1)) {
                            clientHandler.selectEntityNumWork(ClientHandler.allRoleMap.get(s1), sc);
                        } else {
                            if (userServiceCache.getUserInMap().get(clientHandler.selfId).getRoleIdList().contains(s1)) {
                                System.out.println("----你选择的是自己的角色，当前状态为：" + JsonFormat.printToString(roleServiceCache.getRoleInMap().get(s1).getRole()));
                            } else {
                                String userId2 = roleServiceCache.getRoleInMap().get(s1).getRole().getUserId();
                                while (true) {
                                    logger.info("你选择的是：{} 用户,请选择需要的操作\n1、私聊\n2、砍他\n0、返回上一层", userId2);
                                    String s2 = sc.nextLine();
                                    if ("0".equals(s2)) {
                                        break;
                                    } else if ("1".equals(s2)) {
                                        clientHandler.sendOneToOneChatOld(userId2);
                                        while (true) {
                                            logger.info("输入0会退出会话！");
                                            String content = sc.nextLine();
                                            if ("0".equals(content)) {
                                                break;
                                            }
                                            clientHandler.sendOneToOneChat(userId2, content);
                                            logger.info("我说：{}", content);
                                        }
                                    } else if ("2".equals(s2)) {
                                        clientHandler.sendPvpSceneMessage(userId2);
                                        break;
                                    }
                                }
                            }
                        }
                        break;
                    }
                    break;
                case 5:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    clientHandler.sendWeaponryMessage(CommonBackpack.GET_WEAPONRY, "1", null, null);
                    clientHandler.sendItemMessage(CommonBackpack.GET_ITEM, "1", null, null, null);
                    UserServiceCache.UserIn userIn = userServiceCache.getUserInMap().get(clientHandler.selfId);
                    while (true) {
                        logger.info("请输入指令：\n" +
                                "1、装备\n" +
                                "2、物品\n" +
                                "其他任意返回上一层。");
                        String s1 = sc.nextLine();
                        if ("1".equals(s1)) {
                            System.out.println("请输入指令：");
                            userIn.getWeaponryMap().values().forEach(weaponry -> {
                                System.out.println(weaponry.getSelfWeaponryId() + "、 " + JsonFormat.printToString(weaponry));
                            });
                            System.out.println("0、返回主菜单。");
                            String s2 = sc.nextLine();
                            if ("0".equals(s2)) {
                                break;
                            }
                            if (!userIn.getWeaponryMap().containsKey(s2)) {
                                System.out.println("输入有误，请重新输入！！！");
                                continue;
                            }
                            while (true) {
                                logger.info("你选择了" +
                                        JsonFormat.printToString(userIn.getWeaponryMap()
                                                .get(s2)) +
                                        "请输入指令：\n" +
                                        "1、使用\n" +
                                        "2、脱下\n" +
                                        "3、修理\n" +
                                        "其他任意返回上一层。");
                                GameEntity.Weaponry weaponry = userIn.getWeaponryMap().get(s2);
                                String s3 = sc.nextLine();
                                if ("1".equals(s3)) {
                                    if (!weaponry.getUsage().equals(BackpackLabel.WEAPONRY_UNUSED)) {
                                        System.out.println("装备已经被使用！！");
                                    } else if (weaponry.getUsage().equals(BackpackLabel.WEAPONRY_UNUSED)) {
                                        logger.info("请选择使用的目标对象：");
                                        List<String> roleIdList = userServiceCache.getUserInMap().get(clientHandler.selfId).getRoleIdList();
                                        for (String roleId : roleIdList) {
                                            GameEntity.Role role = roleServiceCache.getRoleInMap().get(roleId).getRole();
                                            logger.info("{} : {}", role.getAllRole().getAllRoleId(), JsonFormat.printToString(role));
                                        }
                                        String s4 = sc.nextLine();
                                        if (roleIdList.contains(s4)) {
                                            clientHandler.sendWeaponryMessage(CommonBackpack.UPDATE_WEAPONRY_USAGE_USE,
                                                    s4, weaponry.getBackpack().getBackpackId(), weaponry);
                                        } else {
                                            logger.info("角色选择有误！");
                                        }
                                    }
                                    break;
                                } else if ("2".equals(s3)) {
                                    if (weaponry.getUsage().equals(BackpackLabel.WEAPONRY_UNUSED)) {
                                        System.out.println("装备已经是未使用状态！！");
                                    } else if (!weaponry.getUsage().equals(BackpackLabel.WEAPONRY_UNUSED)) {
                                        logger.info("请选择使用的目标对象：");
                                        List<String> roleIdList = userServiceCache.getUserInMap().get(clientHandler.selfId).getRoleIdList();
                                        for (String roleId : roleIdList) {
                                            GameEntity.Role role = roleServiceCache.getRoleInMap().get(roleId).getRole();
                                            logger.info("{} : {}", role.getAllRole().getAllRoleId(), JsonFormat.printToString(role));
                                        }
                                        String s4 = sc.nextLine();
                                        if (roleIdList.contains(s4)) {
                                            clientHandler.sendWeaponryMessage(CommonBackpack.UPDATE_WEAPONRY_USAGE_UNUSED,
                                                    s4, weaponry.getBackpack().getBackpackId(), weaponry);
                                        }
                                    }
                                    break;
                                } else if ("3".equals(s3)) {
                                    //todo:这里编写发送更新装备耐久度请求，服务端根据逻辑判断修理。
                                    //todo 钩子，关闭线程之前需要完成的事，最基本的需要让数据库线程任务处理完！
//                                    Runtime.getRuntime().addShutdownHook();
                                    break;
                                } else {
                                    break;
                                }
                            }
                        } else if ("2".equals(s1)) {
                            System.out.println("请输入指令：");
                            itemServiceCache.getItemInMap().values().forEach(itemIn -> {
                                if (itemIn.getItem().getCount() >= 1) {
                                    System.out.println(itemIn.getItem().getBackpack().getBackpackId()
                                            + "、 " + JsonFormat.printToString(itemIn.getItem()));
                                }
                            });
                            System.out.println("0、返回主菜单。");
                            String s2 = sc.nextLine();
                            if ("0".equals(s2)) {
                                break;
                            }
                            if (!itemServiceCache.getItemInMap().containsKey(s2)) {
                                System.out.println("输入有误，请重新输入！！！");
                                continue;
                            }
                            while (true) {
                                logger.info("你选择了" +
                                        JsonFormat.printToString(itemServiceCache.getItemInMap()
                                                .get(s2).getItem()) +
                                        "请输入指令：\n" +
                                        "1、使用\n" +
                                        "其他任意返回上一层。");
                                String s3 = sc.nextLine();
                                GameEntity.Item item = itemServiceCache.getItemInMap().get(s2).getItem();
                                if ("1".equals(s3)) {
                                    if (item.getCount() <= 0) {
                                        System.out.println("物品余额不足！！");
                                    } else if (item.getBackpack().getBackpackId().equals("500003")) {
                                        logger.info("请输入需要进入的场景：");
                                        String s4 = sc.nextLine();
                                        clientHandler.sendItemMessage(CommonBackpack.UPDATE_ITEM_REDUCE_COUNT,
                                                userServiceCache.getUserInMap().get(clientHandler.selfId).getRoleIdList()
                                                        .get(0), item.getBackpack().getBackpackId(), item, s4);
                                    } else {
                                        logger.info("请选择使用的目标对象：");
                                        List<String> roleIdList = userServiceCache.getUserInMap().get(clientHandler.selfId).getRoleIdList();
                                        for (String roleId : roleIdList) {
                                            GameEntity.Role role = roleServiceCache.getRoleInMap().get(roleId).getRole();
                                            logger.info("{} : {}", role.getAllRole().getAllRoleId(), JsonFormat.printToString(role));
                                        }
                                        String s4 = sc.nextLine();
                                        if (roleIdList.contains(s4)) {
                                            clientHandler.sendItemMessage(CommonBackpack.UPDATE_ITEM_REDUCE_COUNT,
                                                    s4, item.getBackpack().getBackpackId(), item, null);
                                        }
                                    }
                                    break;
                                } else {
                                    break;
                                }
                            }
                        } else {
                            break;
                        }
                    }
                    break;
                case 6:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    while (true) {
                        commodityServiceCache.getCommodityInMap().values().forEach(commodityIn -> {
                            System.out.println(commodityIn.getCommodity().getId()
                                    + "、" + JsonFormat.printToString(commodityIn.getCommodity()));
                        });
                        System.out.println("0、返回主菜单。");
                        String s2 = sc.nextLine();
                        if ("0".equals(s2)) {
                            break;
                        }
                        if (!commodityServiceCache.getCommodityInMap().containsKey(s2)) {
                            System.out.println("输入有误，请重新输入！！！");
                            continue;
                        }
                        while (true) {
                            logger.info("你选择了" +
                                    JsonFormat.printToString(commodityServiceCache
                                            .getCommodityInMap().get(s2).getCommodity()) +
                                    "请输入指令：\n" +
                                    "1、购买\n" +
                                    "其他任意返回上一层。");
                            String s3 = sc.nextLine();
                            if ("1".equals(s3)) {
                                logger.info("请输入需要购买的数量：");
                                String s4 = sc.nextLine();
                                if (!isNumeric(s4)) {
                                    logger.info("输入有误!!");
                                    break;
                                }
                                clientHandler.sendShopMessage(CommonShop.GAME_SHOP_COMMODITY, s2, Integer.parseInt(s4));
                                break;
                            } else {
                                break;
                            }
                        }
                        break;
                    }
                    break;
                case 7:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    clientHandler.sendWorldPlayerChatOld(clientHandler.selfId);
                    while (true) {
                        logger.info("输入0会退出会话！");
                        String content = sc.nextLine();
                        if ("0".equals(content)) {
                            break;
                        }
                        clientHandler.sendWorldPlayerChat(content);
                        logger.info("我说：{}", content);
                    }
                    break;
                case 8:
                    if (!isLogin()) {
                        logger.info("用户未登录，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    logger.info("输入角色职业：");
                    String profession = sc.nextLine();
                    logger.info("输入角色名：");
                    String roleName = sc.nextLine();
                    clientHandler.sendCreateRole(Common.GAME_CREATE_ROLE, profession, roleName);
                    break;
                case 9:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    logger.info("请选择对应的邮件进行领取操作：\n");
                    int i = 0;
                    Map<Integer, String> idToEmailIdMap = new HashMap<>();
                    for (GameEmail.Email email : userServiceCache.getEmailMap().values()) {
                        idToEmailIdMap.put(++i, email.getEmailId());
                        logger.info("{}: {}", i, JsonFormat.printToString(email));
                    }
                    logger.info("0、返回主菜单。");
                    String s2 = sc.nextLine();
                    if ("0".equals(s2)) {
                        break;
                    }
                    clientHandler.sendEmail(CommonEmail.CLAIM, idToEmailIdMap.get(Integer.valueOf(s2)));
                    break;
                case 10:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    logger.info("请选择操作：\n" +
                            "1、创建队伍\n" +
                            "2、加入队伍\n" +
                            "3、离开队伍\n" +
                            "0、返回主菜单");
                    String s1 = sc.nextLine();
                    switch (s1) {
                        case "1":
                            logger.info("请输入创建队伍的名称：");
                            String teamName = sc.nextLine();
                            clientHandler.sendTeamMsg(CommonTeam.CREATE, teamName);
                            break;
                        case "2":
                            clientHandler.sendTeamMsg(CommonTeam.GET_ALL, "");
                            logger.info("请输入想要加入的队伍名：");
                            String teamName1 = sc.nextLine();
                            clientHandler.sendTeamMsg(CommonTeam.JOIN, teamName1);
                            break;
                        case "3":
                            clientHandler.sendTeamMsg(CommonTeam.OUT, "");
                            break;
                        case "0":
                            break;
                        default:
                            logger.info("输入有误！");
                            break;
                    }
                    break;
                case 11:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    logger.info("请选择操作：\n" +
                            "1、请求建立交易\n" +
                            "2、接受建立交易\n" +
                            "3、关闭交易连接\n" +
                            "4、请求交易物品\n" +
                            "5、交易消息选择\n" +
                            "0、返回主菜单");
                    String s3 = sc.nextLine();
                    switch (s3) {
                        case "1":
                            logger.info("请输入想要交易的用户Id");
                            String s4 = sc.nextLine();
                            clientHandler.sendTradingMsg(CommonTrading.REQUEST, s4, null);
                            break;
                        case "2":
                            logger.info("请输入接受交易的用户Id");
                            String s5 = sc.nextLine();
                            clientHandler.sendTradingMsg(CommonTrading.RESPONSE, s5, null);
                            break;
                        case "3":
                            clientHandler.sendTradingMsg(CommonTrading.CANCEL, null, null);
                            break;
                        case "4":
                            logger.info("请选择需要交易的货物类型：" +
                                    ShopLabel.MONEY_TYPE_GOLD + "、金币" +
                                    BackpackLabel.WEAPONRY + "、武器" +
                                    BackpackLabel.ITEM + "、物品");
                            String s6 = sc.nextLine();
                            String stringId = userServiceCache.getUserInMap().get(clientHandler.selfId).getInTradingUserId();
                            if (stringId == null) {
                                logger.info("发送交易消息失败，交易连接未建立！");
                                break;
                            }
                            GameTrading.Trading.Builder tb = GameTrading.Trading.newBuilder();
                            tb.setSenderId(clientHandler.selfId);
                            tb.setReceiverId(stringId);
                            if (Integer.parseInt(s6) == ShopLabel.MONEY_TYPE_GOLD) {
                                logger.info("当前金币数量：{};请输入需要交易的金币数量：", userServiceCache.getUserInMap()
                                        .get(clientHandler.selfId).getUser().getGold());
                                String s7 = sc.nextLine();
                                tb.setType(ShopLabel.MONEY_TYPE_GOLD);
                                tb.setGold(Integer.parseInt(s7));
                            } else if (Integer.parseInt(s6) == BackpackLabel.WEAPONRY) {
                                logger.info("当前背包未使用的武器详情：");
                                userServiceCache.getUserInMap().get(clientHandler.selfId).getWeaponryMap().values().stream().filter
                                        (weaponry -> weaponry.getUsage().equals(BackpackLabel.WEAPONRY_UNUSED)).collect(Collectors.toList())
                                        .forEach(weaponry -> System.out.println(weaponry.getSelfWeaponryId() + "、 " + JsonFormat.printToString(weaponry)));
                                logger.info("请输入需要交易的武器Id:");
                                String s7 = sc.nextLine();
                                tb.setType(BackpackLabel.WEAPONRY);
                                tb.addBackpackIdToCountMap(GameTrading.BackpackIdToCountMap.newBuilder().setBackpackId(s7).setCount(1).build());
                            } else if (Integer.parseInt(s6) == BackpackLabel.ITEM) {
                                logger.info("当前背包物品详情：");
                                itemServiceCache.getItemInMap().values().forEach(itemIn -> {
                                    if (itemIn.getItem().getCount() >= 1) {
                                        System.out.println(itemIn.getItem().getBackpack().getBackpackId()
                                                + "、 " + JsonFormat.printToString(itemIn.getItem()));
                                    }
                                });
                                logger.info("请输入需要交易的物品Id：");
                                String s7 = sc.nextLine();
                                logger.info("请输入需要交易的物品数量：");
                                String s8 = sc.nextLine();
                                tb.setType(BackpackLabel.ITEM);
                                tb.addBackpackIdToCountMap(GameTrading.BackpackIdToCountMap.newBuilder()
                                        .setBackpackId(s7).setCount(Integer.parseInt(s8)).build());
                            }
                            logger.info("期望得到的元宝数量：");
                            String s8 = sc.nextLine();
                            tb.setIngot(Integer.parseInt(s8));
                            tb.setTradingId(UUIDUtil.getUUID());
                            GameTrading.Trading trading = tb.build();
                            userServiceCache.getUserInMap().get(clientHandler.selfId).getTradingIdToTradingMap().put(trading.getTradingId(), trading);
                            clientHandler.sendTradingMsg(CommonTrading.SEND_TRADING, stringId, trading);
                            break;
                        case "5":
                            String inTradingUserId = userServiceCache.getUserInMap().get(clientHandler.selfId).getInTradingUserId();
                            userServiceCache.getUserInMap().get(clientHandler.selfId).getInTradingUserId();
                            for (Map.Entry<String, GameTrading.Trading> entry : userServiceCache
                                    .getUserInMap().get(inTradingUserId).getTradingIdToTradingMap().entrySet()) {
                                System.out.println(entry.getKey() + "、" + JsonFormat.printToString(entry.getValue()));
                            }
                            logger.info("请输入需要处理的交易Id:");
                            String s7 = sc.nextLine();
                            if (!userServiceCache.getUserInMap().get(inTradingUserId).getTradingIdToTradingMap().containsKey(s7)) {
                                logger.info("你选择的消息不存在！");
                                break;
                            }
                            logger.info("你选择的是：{}", JsonFormat.printToString(userServiceCache
                                    .getUserInMap().get(inTradingUserId).getTradingIdToTradingMap().get(s7)));
                            logger.info("请选择对应操作：" +
                                    "1、同意这笔交易\t" +
                                    "2、拒绝这笔交易");
                            String s9 = sc.nextLine();
                            if ("1".equals(s9)) {
                                clientHandler.sendTradingMsg(CommonTrading.RECEIVE_TRADING_AGREE, s7, null);
                            } else if ("2".equals(s9)) {
                                clientHandler.sendTradingMsg(CommonTrading.RECEIVE_TRADING_DISAGREE, s7, null);
                            }
                            break;
                        case "0":
                            break;
                        default:
                            break;
                    }
                    break;
                case 12:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    clientHandler.sendGuildMsg(CommonGuild.GET_ALL);
                    while (true) {
                        logger.info("请选择操作：\n" +
                                "1、查看公会基础信息\n" +
                                "2、公会列表\n" +
                                "3、管理员公会管理\n" +
                                "4、创建公会\n" +
                                "5、退出公会\n" +
                                "6、公会仓库\n" +
                                "0、返回主菜单");
                        String s4 = sc.nextLine();
                        if ("0".equals(s4)) {
                            break;
                        }
                        switch (s4) {
                            case "1":
                                if (userServiceCache.getUserInMap().get(clientHandler.selfId).getGuildId() == null) {
                                    logger.info("你没有加入公会,可以选择查看公会列表加入公会或者自己创建公会！");
                                    break;
                                }
                                logger.info("公会详细信息：{}", JsonFormat.printToString(guildCache.getGuild()));
                                logger.info("公会成员信息：");
                                for (GameGuild.GuildUser guildUser : guildCache.getGuildUserList()) {
                                    logger.info("{}", JsonFormat.printToString(guildUser));
                                }
                                logger.info("仓库详细信息：");
                                if (guildCache.getGuildWarehouseList() != null) {
                                    for (GameGuild.GuildWarehouse guildWarehouse : guildCache.getGuildWarehouseList()) {
                                        logger.info("{}", JsonFormat.printToString(guildWarehouse));
                                    }
                                }
                                break;
                            case "2":
                                if (guildCache.getSimpleAllGuildList().size() == 0) {
                                    logger.info("目前没有任何公会，快去创建吧！");
                                    break;
                                }
                                for (GameGuild.SimpleAllGuild simpleAllGuild : guildCache.getSimpleAllGuildList()) {
                                    logger.info("{}", JsonFormat.printToString(simpleAllGuild));
                                }
                                if (userServiceCache.getUserInMap().get(clientHandler.selfId).getGuildId() == null) {
                                    logger.info("你没有加入公会可以输入上面的公会Id进行申请加入公会哦！");
                                    String s5 = sc.nextLine();
                                    for (GameGuild.SimpleAllGuild simpleAllGuild : guildCache.getSimpleAllGuildList()) {
                                        if (simpleAllGuild.getGuildId().equals(s5)) {
                                            clientHandler.sendGuildMsg(CommonGuild.APPLY_GUILD_USER,
                                                    clientHandler.selfId, GameGuild.Guild.newBuilder().setGuildId(s5).build());
                                            break;
                                        }
                                    }
                                }
                                break;
                            case "3":
                                if (userServiceCache.getUserInMap().get(clientHandler.selfId).getGuildId() == null) {
                                    logger.info("你没有加入公会,可以选择查看公会列表加入公会或者自己创建公会！");
                                    break;
                                }
                                clientHandler.sendGuildMsg(CommonGuild.GET_APPLY_USER_ID, guildCache.getGuild());
                                GameGuild.GuildUser guildUser = null;
                                for (GameGuild.GuildUser guildUser1 : guildCache.getGuildUserList()) {
                                    if (guildUser1.getUserId().equals(clientHandler.selfId)) {
                                        guildUser = guildUser1;
                                        break;
                                    }
                                }
                                if (guildUser.getJob() == GuildJobLabel.HEADER.value) {
                                    logger.info("请选择操作：\n" +
                                            "1、更改会员职位\n" +
                                            "2、查看申请列表\n" +
                                            "3、踢人\n" +
                                            "其他任意键返回上一层");
                                    String s5 = sc.nextLine();
                                    switch (s5) {
                                        case "1":
                                            for (GameGuild.GuildUser guildUser1 : guildCache.getGuildUserList()) {
                                                if (!guildUser1.getUserId().equals(clientHandler.selfId)) {
                                                    logger.info("{}", JsonFormat.printToString(guildUser1));
                                                }
                                            }
                                            logger.info("请输入需要更改职位的会员Id:");
                                            String s6 = sc.nextLine();
                                            logger.info("请输入变更后的职位：" +
                                                    "1、会长" +
                                                    "2、副会长" +
                                                    "3、普通成员");
                                            String s7 = sc.nextLine();
                                            int job = Integer.parseInt(s7);
                                            for (GameGuild.GuildUser guildUser1 : guildCache.getGuildUserList()) {
                                                if (guildUser1.getUserId().equals(s6)) {
                                                    if (guildUser1.getJob() == job) {
                                                        logger.info("会员职位与您输入一样，无需变更！");
                                                        break;
                                                    }
                                                    clientHandler.sendTradingMsg(CommonGuild.UPDATE_GUILD_USER_JOB,
                                                            guildUser1.toBuilder().setJob(job).build());
                                                    break;
                                                }
                                            }
                                            logger.info("输入有误！！");
                                            break;
                                        case "2":
                                            logger.info("选择对应的用户Id进行操作。");
                                            for (String applyUserId : guildCache.getApplyUserIdList()) {
                                                logger.info(applyUserId);
                                            }
                                            String s8 = sc.nextLine();
                                            for (String applyUserId : guildCache.getApplyUserIdList()) {
                                                if (s8.equals(applyUserId)) {
                                                    logger.info("1、同意   2、拒绝");
                                                    String s9 = sc.nextLine();
                                                    if ("1".equals(s9)) {
                                                        clientHandler.sendGuildMsg(CommonGuild.ADD_GUILD_USER, s8, guildCache.getGuild());
                                                    } else if ("2".equals(s9)) {
                                                        clientHandler.sendGuildMsg(CommonGuild.APPLY_GUILD_USER_DISAGREE, s8, guildCache.getGuild());
                                                    }
                                                    break;
                                                }
                                            }
                                            break;
                                        case "3":
                                            logger.info("选择对应的用户Id进行踢出。 输入0返回！");
                                            for (GameGuild.GuildUser guildUser1 : guildCache.getGuildUserList()) {
                                                logger.info(JsonFormat.printToString(guildUser1));
                                            }
                                            String s10 = sc.nextLine();
                                            clientHandler.sendGuildMsg(CommonGuild.DELETE_GUILD_USER, s10, guildCache.getGuild());
                                            break;
                                        default:
                                            break;
                                    }
                                } else if (guildUser.getJob() == GuildJobLabel.VICE_HEADER.value) {
                                    logger.info("请选择操作：\n" +
                                            "1、查看申请列表\n" +
                                            "2、踢人\n" +
                                            "其他任意键返回上一层");
                                    String s5 = sc.nextLine();
                                    switch (s5) {
                                        case "1":
                                            logger.info("选择对应的用户Id进行操作。 输入0返回！");
                                            for (String applyUserId : guildCache.getApplyUserIdList()) {
                                                logger.info(applyUserId);
                                            }
                                            String s8 = sc.nextLine();
                                            for (String applyUserId : guildCache.getApplyUserIdList()) {
                                                if (s8.equals(applyUserId)){
                                                    logger.info("1、同意   2、拒绝");
                                                    String s9 = sc.nextLine();
                                                    if ("1".equals(s9)) {
                                                        clientHandler.sendGuildMsg(CommonGuild.ADD_GUILD_USER, s8, guildCache.getGuild());
                                                    } else if ("2".equals(s9)) {
                                                        clientHandler.sendGuildMsg(CommonGuild.APPLY_GUILD_USER_DISAGREE, s8, guildCache.getGuild());
                                                    }
                                                    guildCache.getApplyUserIdList().remove(s8);
                                                    break;
                                                }
                                            }
                                            break;
                                        case "2":
                                            logger.info("选择对应的用户Id进行踢出。 输入0返回！");
                                            for (GameGuild.GuildUser guildUser1 : guildCache.getGuildUserList()) {
                                                logger.info(JsonFormat.printToString(guildUser1));
                                            }
                                            String s10 = sc.nextLine();
                                            clientHandler.sendGuildMsg(CommonGuild.DELETE_GUILD_USER, s10, guildCache.getGuild());
                                            break;
                                        default:
                                            break;
                                    }
                                } else {
                                    logger.info("你不是会长或者副会长没有管理公会的权限！");
                                }
                                break;
                            case "4":
                                if (userServiceCache.getUserInMap().get(clientHandler.selfId).getGuildId() != null) {
                                    logger.info("你已经在公会中，不允许再创建公会！");
                                    break;
                                }
                                logger.info("请输入公会名：");
                                String s5 = sc.nextLine();
                                logger.info("请输入公告：");
                                String s6 = sc.nextLine();
                                GameGuild.Guild.Builder gb = GameGuild.Guild.newBuilder();
                                gb.setGuildId(UUIDUtil.getUUID());
                                gb.setName(s5);
                                gb.setNotice(s6);
                                gb.setLevel(1);
                                gb.setExperience(0);
                                gb.setHeaderId(clientHandler.selfId);
                                clientHandler.sendGuildMsg(CommonGuild.ADD_GUILD, gb.build());
                                break;
                            case "5":
                                if (userServiceCache.getUserInMap().get(clientHandler.selfId).getGuildId() == null) {
                                    logger.info("你不在公会中，没啥好退出的！");
                                    break;
                                }
                                clientHandler.sendGuildMsg(CommonGuild.DELETE_GUILD, guildCache.getGuild());
                                break;
                            case "6":
                                if (userServiceCache.getUserInMap().get(clientHandler.selfId).getGuildId() == null) {
                                    logger.info("你不在公会中，哪来的公会仓库！");
                                    break;
                                }
                                //todo 公会仓库
                            default:
                                break;
                        }
                    }
                    break;
                case 13:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    clientHandler.sendTradingShopMsg(CommonTradingShop.GET_ALL);
                    while (true){
                        logger.info("请选择操作：\n" +
                                "1、查看全部拍卖物品信息\n" +
                                "2、查看物品的竞拍记录\n" +
                                "3、竞拍物品\n" +
                                "4、上架物品\n" +
                                "5、我的竞拍记录\n" +
                                "6、我的上架物品记录\n" +
                                "0、返回主菜单");
                        String s4 = sc.nextLine();
                        if ("0".equals(s4)){
                            break;
                        }
                        switch (s4) {
                            case "1":
                                for (TradingShopCache.TradingShopIn tradingShopIn : tradingShopCache.getTradingShopInMap().values()) {
                                    logger.info(JsonFormat.printToString(tradingShopIn.getTradingShop()));
                                }
                                break;
                            case "2":
                                logger.info("请输入您要查看的竞拍物品Id：");
                                String s5 = sc.nextLine();
                                if (!tradingShopCache.getTradingShopInMap().containsKey(s5)) {
                                    logger.info("别瞎JB输入，拍品压根不存在！！");
                                    break;
                                }
                                for (GameTradingShop.TradingShopRecord tradingShopRecord :
                                        tradingShopCache.getTradingShopInMap().get(s5).getTradingShopRecordList()) {
                                    logger.info(JsonFormat.printToString(tradingShopRecord));
                                }
                                break;
                            case "3":
                                logger.info("请选择竞拍物品的id：");
                                String s6 = sc.nextLine();
                                if (!tradingShopCache.getTradingShopInMap().containsKey(s6)) {
                                    logger.info("物品不存在，别瞎JB输入！！");
                                    break;
                                }
                                int tradingShopType = tradingShopCache.getTradingShopInMap().get(s6).getTradingShop().getTradingShopType();
                                if (tradingShopType == TradingShopLabel.FIXED_PRICE) {
                                    clientHandler.sendTradingShopMsg(CommonTradingShop.BUY_FIXED_PRICE,
                                            tradingShopCache.getTradingShopInMap().get(s6).getTradingShop());
                                } else {
                                    logger.info("你选择的是拍卖物品，请输入你的出价金额：");
                                    String buyNumber = sc.nextLine();
                                    if (!isNumeric(buyNumber)) {
                                        logger.info("出价有误，输入为非数字！！");
                                        break;
                                    }
                                    if (tradingShopCache.getTradingShopInMap().get(s6).getTradingShopRecordList().size() == 0) {
                                        if (tradingShopCache.getTradingShopInMap().get(s6)
                                                .getTradingShop().getIngot() > Integer.parseInt(buyNumber)) {
                                            logger.info("出价金额低于拍品最低价，出价失败！");
                                            break;
                                        }
                                    }else {
                                        if (tradingShopCache.getTradingShopInMap().get(s6).getTradingShopRecordList()
                                                .get(0).getIngot() >= Integer.parseInt(buyNumber)) {
                                            logger.info("出价金额需要高于当前最高价,出价失败！！");
                                            break;
                                        }
                                    }
                                    GameTradingShop.TradingShopRecord.Builder tsrb = GameTradingShop.TradingShopRecord.newBuilder();
                                    tsrb.setTradingShopId(s6);
                                    tsrb.setUserId(tradingShopCache.getTradingShopInMap().get(s6).getTradingShop().getUserId());
                                    tsrb.setRecordId(UUIDUtil.getUUID());
                                    tsrb.setIngot(Long.parseLong(buyNumber));
                                    tsrb.setBackpackId(tradingShopCache.getTradingShopInMap().get(s6).getTradingShop().getBackpackId());
                                    tsrb.setBuyId(clientHandler.selfId);
                                    tsrb.setCreateTime(System.currentTimeMillis());
                                    clientHandler.sendTradingShopMsg(CommonTradingShop.BUY_AUCTION,
                                            tradingShopCache.getTradingShopInMap().get(s6).getTradingShop(), tsrb.build());
                                }
                                break;
                            case "4":
                                logger.info("请选择需要需要上架物品拍卖模式：\n" +
                                        "1、一口价\n" +
                                        "2、拍卖");
                                String s7 = sc.nextLine();
                                if ("1".equals(s7) || "2".equals(s7)) {
                                    logger.info("请选择需要拍卖的物品Id：");
                                    for (GameEntity.Weaponry weaponry : userServiceCache
                                            .getUserInMap().get(clientHandler.selfId).getWeaponryMap().values()) {
                                        if (weaponry.getUsage().equals(BackpackLabel.WEAPONRY_UNUSED)) {
                                            logger.info(JsonFormat.printToString(weaponry));
                                        }
                                    }
                                    String s8 = sc.nextLine();
                                    GameTradingShop.TradingShop.Builder tsb = GameTradingShop.TradingShop.newBuilder();
                                    if (!userServiceCache.getUserInMap().get(clientHandler.selfId).getWeaponryMap().containsKey(s8)) {
                                        logger.info("输入的物品不存在！！");
                                        break;
                                    }
                                    logger.info("请输入价格：");
                                    String s9 = sc.nextLine();
                                    tsb.setUserId(clientHandler.selfId);
                                    tsb.setType(BackpackLabel.WEAPONRY);
                                    tsb.setTradingShopId(UUIDUtil.getUUID());
                                    tsb.setBackpackId(userServiceCache.getUserInMap().get(clientHandler.selfId)
                                            .getWeaponryMap().get(s8).getBackpack().getBackpackId());
                                    tsb.setIngot(Long.parseLong(s9));
                                    if ("1".equals(s7)) {
                                        tsb.setTradingShopType(TradingShopLabel.FIXED_PRICE);
                                        clientHandler.sendTradingShopMsg(CommonTradingShop.ADD_FIXED_PRICE, s8, tsb.build());
                                    } else {
                                        tsb.setTradingShopType(TradingShopLabel.AUCTION);
                                        clientHandler.sendTradingShopMsg(CommonTradingShop.ADD_AUCTION, s8, tsb.build());
                                    }
                                } else {
                                    logger.info("输入有误！");
                                }
                                break;
                            case "5":
                                clientHandler.sendTradingShopMsg(CommonTradingShop.GET_USER_ALL_BUY_RECORD);
                                break;
                            case "6":
                                clientHandler.sendTradingShopMsg(CommonTradingShop.GET_USER_ALL_USER_ID_RECORD);
                                break;
                            default:
                                logger.info("输入错误！！！！");
                                break;
                        }
                    }
                case 14:
                    if (!isLoginAndIsRole()) {
                        logger.info("用户未登录或者还未创建角色，请进行对应操作之后再继续游戏！！");
                        break;
                    }
                    UserServiceCache.UserIn userIn1 = userServiceCache.getUserInMap().get(clientHandler.selfId);
                    logger.info("获取到当前用户的成就任务：");
                    for (GameTask.Task task : userIn1.getTaskSonType2Task().values()){
                        logger.info(JsonFormat.printToString(task));
                    }
                    break;
                default:
                    logger.info("输入有误，请重新输入, code : {}", code);
                    break;
            }
        }
    }
    private boolean isLoginAndIsRole() {
        return clientHandler.login_success && clientHandler.isRole;
    }

    private boolean isLogin() {
        return clientHandler.login_success;
    }

    /**
     * 判断输入的是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}
